package com.graduate.emos.wx.config.shiro;

import com.graduate.emos.wx.common.util.SystemConstants;
import com.graduate.emos.wx.db.pojo.TbUser;
import com.graduate.emos.wx.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Set;

@Component
public class OAuth2Realm extends AuthorizingRealm {

    //注入JWT工具类
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;
    @Autowired
    private SystemConstants constants;


    //认证对象是否支持
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    //授权(验证权限时调用)
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        /*获取用户信息,这里的用户信息来源于在认证方法(doGetAuthenticationInfo)中构造认证对象时传入的*/
        TbUser user = (TbUser) principalCollection.getPrimaryPrincipal();
        /*查询用户的权限列表*/
        Set<String> permsSet = userService.searchUserPermissions(user.getId());
        /*把权限列表添加到info对象中*/
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    //认证(用户登录时调用)
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        /*获取令牌*/
        String token = (String) authenticationToken.getPrincipal();

        /*从Token中解析用户id*/
        int userId = jwtUtil.getUserId(token);

        /*查询用户信息*/
        TbUser user = userService.searchUserById(userId);
        if (Objects.isNull(user))
            throw new LockedAccountException(constants.USER_ACCOUNT_LOCK_MSG);

        /*使用user,token,认证对象名称通过(getName获取)构造认证对象*/
        AuthenticationInfo info = new SimpleAuthenticationInfo(user, token, getName());
        return info;
    }
}
